import { FormItemProp } from 'element-plus'
import { ref } from 'vue'
import _ from 'lodash'

/**
 * 表单验证服务
 * @param {Array<string>} formItemNames 表单项名称集合
 */
function useFormValidateService(formItemNames: Array<string>) {
  const _formItemNames = ref(_.cloneDeep(formItemNames))

  /**
   * 表单验证结果
   */
  const formValidateResult = ref<Record<string, boolean>>({})
  setFormValidareResultDefault()

  /**
   * 表单验证事件
   * @param {string} prop - 表单项的prop属性的值
   * @param {boolean} isValid - 表单项的验证结果
   */
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    formValidateResult.value[prop as string] = isValid
  }

  /**
   * 重置表单验证结果方法
   */
  const resetFormValidateResult = () => {
    const keys = Object.keys(formValidateResult.value)
    keys.forEach((item) => {
      formValidateResult.value[item] = true
    })
  }

  /**
   * 添加表单项方法
   * @param {string} formItemName - 表单项名称
   */
  const addFormItemName = (formItemName: string) => {
    _formItemNames.value.push(formItemName)
    setFormValidareResultDefault()
  }

  /**
   * 移除表单项方法
   * @param {string} formItemName - 表单项名称
   */
  const removeFormItemName = (formItemName: string) => {
    const index = _formItemNames.value.findIndex((item) => item === formItemName)
    _formItemNames.value.splice(index, 1)
  }

  /**
   * 重置表单项结果方法
   */
  function setFormValidareResultDefault() {
    _formItemNames.value.forEach((formItemName) => {
      formValidateResult.value[formItemName] = true
    })
  }

  return {
    formValidateResult,
    addFormItemName,
    removeFormItemName,
    handleFormValidate,
    resetFormValidateResult,
  }
}

export default useFormValidateService
